<template>
  <div class="orderadd">
    <div class="orderadd-header">
      <div class="orderadd-title">添加订单</div>
      <!-- <div class="orderadd-buttons">
        <el-button class="adduser-button" type="primary">新增用户</el-button>
      </div> -->
    </div>
    <div class="orderadd-content">
      <el-scrollbar height="100%">
        <el-form
          :model="orderform"
          class="addorder-form"
          label-width="180"
          style="width: 70%"
          ref="ruleFormRef"
          :rules="rules"
        >
          <el-form-item label="拍货日期" prop="buygoodsDate">
            <el-date-picker
              v-model="orderform.buygoodsDate"
              type="date"
              placeholder="请选择拍货日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="销售员" prop="salespersonName">
            <el-input class="form-input" v-model="orderform.salespersonName" />
          </el-form-item>
          <el-form-item label="店名" prop="storename">
            <el-input class="form-input" v-model="orderform.storename" />
          </el-form-item>
          <el-form-item label="接单平台" prop="orderplatform">
            <el-input class="form-input" v-model="orderform.orderplatform" />
          </el-form-item>
          <el-form-item label="订单编号" prop="ordernumber">
            <el-input class="form-input" v-model="orderform.ordernumber" />
          </el-form-item>
          <el-form-item label="收件人" prop="recipients">
            <el-input class="form-input" v-model="orderform.recipients" />
          </el-form-item>
          <el-form-item label="门市地址" prop="address">
            <el-input class="form-input" v-model="orderform.address" />
          </el-form-item>
          <el-form-item label="颜色尺码" prop="colorSize">
            <el-input class="form-input" v-model="orderform.colorSize" />
          </el-form-item>
          <el-form-item label="数量" prop="num">
            <el-input-number
              v-model="orderform.num"
              :step="1"
              step-strictly
              :min="1"
            />
          </el-form-item>
          <el-form-item label="商品主图" prop="goodsimg">
            <el-upload
              v-if="orderform.goodsimg == ''"
              action="http://47.99.66.117:5500/api/upload"
              list-type="picture-card"
              :show-file-list="false"
              :on-success="getuploadimgsuccess"
            >
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="active-uploadimgs" v-if="orderform.goodsimg != ''">
              <img
                :src="imgurls(orderform.goodsimg)"
                class="avatar el-upload-list__item-thumbnail"
                style="height: 148px"
              />
              <el-icon
                style="margin-left: 20px; cursor: pointer"
                @click="orderform.goodsimg = ''"
                ><delete
              /></el-icon>
            </div>
          </el-form-item>
          <el-form-item label="拍货链接" prop="buygoodsUrl">
            <el-input class="form-input" v-model="orderform.buygoodsUrl" />
          </el-form-item>
          <el-form-item label="售價（不含运费）" prop="price">
            <el-input-number
              v-model="orderform.price"
              @change="changepriceFreight"
              :precision="2"
              :min="1"
              :step="10"
            />
          </el-form-item>
          <el-form-item label="运费" prop="freight">
            <el-input-number
              v-model="orderform.freight"
              @change="changepriceFreight"
              :precision="2"
              :min="1"
              :step="10"
            />
          </el-form-item>
          <el-form-item label="售价（含运费）">
            <el-input-number
              v-model="orderform.priceFreight"
              :precision="2"
              :disabled="true"
              :min="1"
              :step="10"
            />
          </el-form-item>
          <el-form-item label="成本" prop="cost">
            <el-input-number
              v-model="orderform.cost"
              :precision="2"
              :min="1"
              :step="10"
            />
          </el-form-item>
          <el-form-item label="结账金额" prop="closingAmount">
            <el-input-number
              v-model="orderform.closingAmount"
              :precision="2"
              :min="1"
              :step="10"
            />
          </el-form-item>
          <el-form-item label="代收金額（先付的不填）">
            <el-input-number
              v-model="orderform.collectionAmount"
              :precision="2"
              :min="0"
              :step="10"
            />
          </el-form-item>
          <el-form-item label="商品名称" prop="goodsName">
            <el-input class="form-input" v-model="orderform.goodsName" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input class="form-input" v-model="orderform.phone" />
          </el-form-item>
          <el-form-item label="物流方式" prop="logistics">
            <el-input class="form-input" v-model="orderform.logistics" />
          </el-form-item>
          <el-form-item label="出货日期" prop="shippingDate">
            <!-- <el-input v-model="orderform.shippingDate" /> -->
            <el-date-picker
              v-model="orderform.shippingDate"
              type="date"
              placeholder="请选择出货日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="国内快递单号">
            <!-- <el-input class="form-input" v-model="orderform.expressNum" /> -->
            <div class="expressnums">
              <div class="expressnum-inputs">
                <el-input v-for="(item, index) in orderform.expressNum" :key="index" class="expressnum-input" v-model="item.value" />
              </div>
              <div class="addexpressnum-button">
                <el-button type="success" @click="addexpressnum">添加</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="快递公司" prop="expressCompanies">
            <el-input class="form-input" v-model="orderform.expressCompanies" />
          </el-form-item>
          <el-form-item label="新竹单号/超商" prop="hsinchuNum">
            <el-input class="form-input" v-model="orderform.hsinchuNum" />
          </el-form-item>
          <el-form-item label="店号" prop="storeNum">
            <el-input class="form-input" v-model="orderform.storeNum" />
          </el-form-item>
          <el-form-item label="代收（做拍货当天就完善）" prop="expressNum">
            <el-input class="form-input" v-model="orderform.collection" />
          </el-form-item>
          <el-form-item label="品名" prop="productName">
            <el-input class="form-input" v-model="orderform.productName" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              class="form-input"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              v-model="orderform.remarks"
            />
          </el-form-item>
          <el-form-item label="重量">
            <el-input class="form-input" v-model="orderform.weight" />
          </el-form-item>
          <el-form-item class="order-addother">
            <div
              v-if="orderform.other.length == 0"
              class="addother-orderbuttons"
            >
              <el-button type="primary" plain @click="addotheritem()"
                >添加其他内容</el-button
              >
            </div>
            <div v-else class="addother-ordertest">
              <div class="othertest-content">
                <div class="othertest-content-title">自定义内容</div>
                <div class="othertest-list">
                  <div
                    class="othertest-item"
                    v-for="(item, index) in orderform.other"
                    :key="index"
                  >
                    <el-input
                      v-model="item.label"
                      style="width: 150px"
                      placeholder="请输入字段名"
                    />
                    <div style="padding: 0 5px">：</div>
                    <el-input
                      v-model="item.value"
                      style="width: 58%"
                      placeholder="请输入字段内容"
                    />
                    <div
                      style="margin-left: 10px; cursor: pointer"
                      @click="deleteotheritem(index)"
                    >
                      <el-icon><delete /></el-icon>
                    </div>
                  </div>
                </div>
                <div class="addother-orderbuttons">
                  <el-button type="primary" plain @click="addotheritem()"
                    >添加其他内容</el-button
                  >
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <div class="orderadd-footer">
      <div class="orderadd-buttons">
        <el-button @click="resetorderform()">重置</el-button>
        <el-button @click="ordersubmit(ruleFormRef)">保存</el-button>
      </div>
    </div>
  </div>
</template>
  
  <script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { addordergoods } from "@/api/order/index.ts";
import { ElMessage, ElMessageBox } from "element-plus";

import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import type {
  UploadFile,
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadFiles,
  FormInstance,
  FormRules,
} from "element-plus";

interface RuleForm {
  buygoodsDate: string;
  salespersonName: string;
  storename: string;
  orderplatform: string;
  ordernumber: string;
  recipients: string;
  address: string;
  colorSize: string;
  num: number;
  goodsimg: string;
  buygoodsUrl: string;
  price: number;
  freight: number;
  priceFreight: number;
  cost: number;
  closingAmount: number;
  collectionAmount: number;
  goodsName: string;
  phone: string;
  logistics: string;
  shippingDate: string;
  expressNum: any;
  expressCompanies: string;
  hsinchuNum: string;
  storeNum: string;
  collection: string;
  productName: string;
  remarks: string;
  weight: string;
  other: any;
  userId: number;
}

const ruleFormRef = ref<FormInstance>();

const activeuser = ref({})

const orderform = reactive<RuleForm>({
  buygoodsDate: "", //拍货日期
  salespersonName: "",
  storename: "",
  orderplatform: "",
  ordernumber: "",
  recipients: "",
  address: "",
  colorSize: "",
  num: 1,
  goodsimg: "",
  buygoodsUrl: "",
  price: 100,
  freight: 5,
  priceFreight: 105,
  cost: 10,
  closingAmount: 100,
  collectionAmount: 0,
  goodsName: "",
  phone: "",
  logistics: "",
  shippingDate: "",
  expressNum: [
    {
      value: "",
    },
  ],
  expressCompanies: "",
  hsinchuNum: "",
  storeNum: "",
  collection: "",
  productName: "",
  remarks: "",
  weight: "",
  other: [],
  userId: 2,
});

const rules = reactive<FormRules<RuleForm>>({
  buygoodsDate: [
    {
      required: true,
      message: "请选择拍货日期",
      trigger: "change",
    },
  ],
  salespersonName: [
    {
      required: true,
      message: "请输入销售员",
      trigger: "blur",
    },
  ],
  storename: [
    {
      required: true,
      message: "请输入店名",
      trigger: "blur",
    },
  ],
  orderplatform: [
    {
      required: true,
      message: "请输入接单平台",
      trigger: "blur",
    },
  ],
  ordernumber: [
    {
      required: true,
      message: "请输入订单编号",
      trigger: "blur",
    },
  ],
  recipients: [
    {
      required: true,
      message: "请输入收件人",
      trigger: "blur",
    },
  ],
  address: [
    {
      required: true,
      message: "请输入门市地址",
      trigger: "blur",
    },
  ],
  colorSize: [
    {
      required: true,
      message: "请输入颜色尺码",
      trigger: "blur",
    },
  ],
  num: [{ required: true, message: "请输入数量", trigger: "blur" }],
  goodsimg: [
    {
      required: true,
      message: "请上传商品主图",
      trigger: "blur",
    },
  ],
  buygoodsUrl: [
    {
      required: true,
      message: "请输入拍货链接",
      trigger: "blur",
    },
  ],
  price: [
    { required: true, message: "请输入售價（不含运费）", trigger: "blur" },
  ],
  freight: [{ required: true, message: "请输入运费", trigger: "blur" }],
  cost: [{ required: true, message: "请输入成本", trigger: "blur" }],
  closingAmount: [
    { required: true, message: "请输入结账金额", trigger: "blur" },
  ],
  goodsName: [
    {
      required: true,
      message: "请输入商品名称",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入电话",
      trigger: "blur",
    },
  ],
  logistics: [
    {
      required: true,
      message: "请输入物流方式",
      trigger: "blur",
    },
  ],
  shippingDate: [
    {
      required: true,
      message: "请输入出货日期",
      trigger: "blur",
    },
  ],
  expressNum: [
    {
      required: true,
      message: "请输入国内快递单号",
      trigger: "blur",
    },
  ],
  expressCompanies: [
    {
      required: true,
      message: "请输入快递公司",
      trigger: "blur",
    },
  ],
  hsinchuNum: [
    {
      required: true,
      message: "请输入新竹单号/超商",
      trigger: "blur",
    },
  ],
  storeNum: [
    {
      required: true,
      message: "请输入店号",
      trigger: "blur",
    },
  ],
  productName: [
    {
      required: true,
      message: "请输入品名",
      trigger: "blur",
    },
  ],
});

const resetorderform = () => {
  for (const key in orderform) {
    if (Object.prototype.hasOwnProperty.call(orderform, key)) {
      delete orderform[key];
    }
  }

  // 添加新的属性
  Object.assign(orderform, {
    buygoodsDate: "", //拍货日期
    salespersonName: "",
    storename: "",
    orderplatform: "",
    ordernumber: "",
    recipients: "",
    address: "",
    colorSize: "",
    num: 1,
    goodsimg: "",
    buygoodsUrl: "",
    price: 100,
    freight: 5,
    priceFreight: 105,
    cost: 10,
    closingAmount: 100,
    collectionAmount: 0,
    goodsName: "",
    phone: "",
    logistics: "",
    shippingDate: "",
    expressNum: [
      {
        value: "",
      },
    ],
    expressCompanies: "",
    hsinchuNum: "",
    storeNum: "",
    collection: "",
    productName: "",
    remarks: "",
    weight: "",
    other: [],
    userId: 2,
  });
  orderform.userId = activeuser.value.userId
};

const ordersubmit = async (formEl: FormInstance | undefined) => {
  // console.log(orderform);
  
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let otherarr = orderform.other;
      let expressNumarr = []
      let otherstatus = 0;
      otherarr.forEach((item) => {
        if (item.value == "" || item.label == "") {
          ElMessage({
            message: "请完善自定义字段",
            type: "warning",
            plain: true,
          });
          otherstatus = 1;
          return;
        }
      });

      orderform.expressNum.forEach(item => {
        if (item.value != '') {
          expressNumarr.push(item.value)
        }
      });

      if (expressNumarr.length == 0) {
        ElMessage({
            message: "请填写最少一个国内快递单号",
            type: "warning",
            plain: true,
          });
          otherstatus = 1;
          return;
      }

      if (otherstatus == 0) {
        let neworderdorm = JSON.parse(JSON.stringify(orderform));
        neworderdorm.other = JSON.stringify(orderform.other);
        neworderdorm.expressNum = expressNumarr.join(',')
        neworderdorm.createrTime = getformattedDate();
        neworderdorm.changeTime = getformattedDate();

        if (expressNumarr.length > 1) {
          neworderdorm.specialtype = '1'
        } else {
          neworderdorm.specialtype = '0'
        }

        // console.log(neworderdorm);

        addordergoods(neworderdorm).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: "订单添加成功",
              type: "success",
            });
          } else {
            ElMessage({
              message: "订单添加失败",
              type: "warning",
              plain: true,
            });
          }
          // console.log(res);
        });
      }
    } else {
      ElMessage({
        message: "请填入必填项",
        type: "warning",
        plain: true,
      });
    }
  });
};

const deleteotheritem = (index) => {
  // orderform.other.splice(index, 1);
  ElMessageBox.confirm("是否删除当前字段", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      orderform.other.splice(index, 1);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

const addotheritem = () => {
  let a = {
    label: "",
    value: "",
  };
  orderform.other.push(a);
};

const imgurls = (goodsimg) => {
  return `http://47.99.66.117:3307/imagest/${goodsimg}`;
};

const getformattedDate = () => {
  let currentTimestamp = Date.now();

  // 将时间戳转换为Date对象
  let date = new Date(currentTimestamp);

  // 获取UTC时间的各个部分
  let year = date.getUTCFullYear();
  let month = date.getUTCMonth() + 1; // 月份从0开始，需要加1
  let day = date.getUTCDate();
  let hours = date.getUTCHours();
  let minutes = date.getUTCMinutes();
  let seconds = date.getUTCSeconds();

  // 北京时间是UTC+8
  hours += 8;
  // 调整小时和日期
  if (hours >= 24) {
    hours -= 24;
    day += 1;
    // 如果天数超过本月最大天数，需要调整月份和年份
    let daysInMonth = new Date(year, month, 0).getDate();
    if (day > daysInMonth) {
      day = 1;
      month += 1;
      if (month > 12) {
        month = 1;
        year += 1;
      }
    }
  }
  // 格式化日期和时间部分
  let formattedDate = `${year}-${String(month).padStart(2, "0")}-${String(
    day
  ).padStart(2, "0")} ${String(hours).padStart(2, "0")}:${String(
    minutes
  ).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;

  return formattedDate;
};

const getuploadimgsuccess = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  // console.log(response);
  if (response.code == 200) {
    ElMessage({
      message: "图片上传成功",
      type: "success",
    });
    orderform.goodsimg = response.data.url;
  }
};

const changepriceFreight = () => {
  orderform.priceFreight = orderform.price + orderform.freight;
};

const addexpressnum = () => {
  let a = {
    value: ''
  }
  orderform.expressNum.push(a)
}

onMounted(() => {
  activeuser.value = JSON.parse(localStorage.getItem("currentUserstr"));
  orderform.userId = activeuser.value.userId
})
</script>
  
  <style scoped>
.orderadd {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.orderadd-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #dcdfe6;
}
.orderadd-title {
  font-size: 16px;
  font-weight: bold;
}
.orderadd-button {
  font-size: 12px;
}
.orderadd-content {
  padding: 10px 0;
  height: calc(100% - 100px);
}
.orderadd-footer {
  height: 60px;
  display: flex;
  justify-content: center;
}

.orderadd-buttons {
  display: flex;
}
.addorder-form {
  margin-left: 100px;
}
.addother-orderbuttons {
  width: 100%;
  height: 50px;
}
.addother-orderbuttons .el-button {
  width: 80%;
  height: 50px;
}
.addother-ordertest {
  width: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 5px;
}
.othertest-content {
  padding: 10px 0;
}
.othertest-item {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.othertest-content-title {
  display: flex;
  justify-content: center;
  font-size: 15px;
  font-weight: bold;
}
.form-input {
  width: 80%;
}
.expressnums {
  display: flex;
  align-items: flex-end;
  justify-content: start;
  width: 100%;
}
.expressnum-inputs {
  display: flex;
  flex-direction: column;
  width: 100%;
}
.expressnum-input {
  width: 100%;
  margin-bottom: 10px;
}
.addexpressnum-button {
  margin-left: 15px;
  margin-bottom: 10px;
}
</style>

<style>
.addorder-form .el-form-item__label {
  font-size: 13px;
}
.addorder-form .el-input {
  font-size: 12px;
}

.order-addother .el-form-item__content {
  margin-left: 0 !important;
}

.active-uploadimgs {
  display: flex;
  align-items: flex-end;
}
</style>